package org.zhao.nettydemos.lab06;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther: xiaohui.zhao
 * @Date: 2021/9/17 16:11
 * @Description:  DateTimeFormatter 是java8中提供的日期时间API中的类 ， 是线程安全的 ， 可以在高并发的场景下直接使用
 */
public class DateTimeFormatterTest {

    // 程序执行的总次数
    private static final int EXECUTE_COUNT = 1000;
    //同时运行的线程数量
    private static final int THREAD_COUNT = 20;

    private static DateTimeFormatter dateTimeFormatter =  DateTimeFormatter.ofPattern("yyyy-MM-dd");


    public static void main(String[] args) throws InterruptedException {
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);

        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<EXECUTE_COUNT;i++){

            executorService.execute(() -> {
                try{
                    semaphore.acquire();
                    try{
                        LocalDate.parse("2020-01-12",dateTimeFormatter);
                    }catch (Exception e){
                        System.out.println("线程 "+Thread.currentThread().getName() + "格式化日期失败");
                        e.printStackTrace();
                        System.exit(1);
                    }

                    semaphore.release();
                }catch (InterruptedException e){
                    System.out.println("信号量发生错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }

}